var printCommonOrderMixin = function (sortDataField) {
  var PrintCommonOrderConfig = function () {
    var template = /* html */ `
      <div class="print-common-order-config">
        <div>
          <el-checkbox v-model="showTableHead">
            <span style="font-size:18px">表格表头是否显示</span>
          </el-checkbox>
        </div>
        <div class="table-config-content">
          <div>表格显示列设置</div>
          <div class="table-config-col-select">
            <div v-for="column in columns" :key="'column_'+column.id" :style="{width:'calc('+maxNum+'em + 25px)'}">
              <el-checkbox v-model="column.isSelect">
                {{column.label}}
              </el-checkbox>
            </div>
          </div>
        </div>
        <div style="text-align:center;margin-top:20px">
          <el-button size="medium" type="primary" @click="ensure">确定</el-button>
        </div>
      </div>
    `;

    return {
      props: {
        config: {
          type: Object,
          required: true
        },
        tableColumns: Array
      },

      data: function () {
        var option = this.getOption();
        return {
          showTableHead: this.config.showTableHead,
          columns: option.columns,
          maxNum: option.maxNum
        };
      },

      methods: {
        getOption: function () {
          var allColumns = this.tableColumns;
          var tableColumns = this.config.tableColumns;
          var selectIds = _.map(tableColumns, 'id');

          var columns = [];
          var maxNum = 0;
          for (var i = 0; i < allColumns.length; i++) {
            var allColumn = allColumns[i];
            var isSelect = selectIds.indexOf(allColumn.id) !== -1;
            var label = allColumn.label;
            if (maxNum < label.length) {
              maxNum = label.length;
            }

            columns.push({
              id: allColumn.id,
              isSelect: isSelect,
              label: label,
              column: allColumn
            });
          }
          return {
            columns: columns,
            maxNum: maxNum
          };
        },

        ensure: function () {
          var config = this.config;

          var columns = this.columns;
          columns = _.filter(columns, {
            isSelect: true
          });

          if (columns.length === 0) {
            this.$alert('表格需要不能没有列显示', '信息');
            return;
          }

          columns = _.map(columns, 'column');
          config.tableColumns = columns;
          config.showTableHead = this.showTableHead;

          this.$emit('update-success', config);
        }
      },

      template: template
    };
  }();

  var PrintCommonOrderConfigButton = function () {
    var template = /* html */ `
      <div class="print-common-order-config-button">
        <el-button :size="size" type="primary" @click="openDialog=true">
          <slot>设置</slot>
        </el-button>

        <el-dialog append-to-body :visible.sync="openDialog" top="10vh" width="60%">
          <div slot="title">
            <slot>设置</slot>
          </div>
          <div style="height:calc(80vh - 54px);overflow:auto">
            <order-config v-if="openDialog" :config="config" :table-columns="tableColumns" @update-success="updateSuccess"></order-config>
          </div>
        </el-dialog>
      </div>
    `;

    return {
      props: {
        config: {
          type: Object,
          required: true
        },
        tableColumns: Array,
        size: {
          type: String,
          default: 'small'
        }
      },

      data: function () {
        return {
          openDialog: false
        };
      },

      created: function () {
        var tableColumns = this.tableColumns;
        var config = this.config;
        if (config.tableColumns === undefined) {
          this.$set(config, 'tableColumns', _.clone(tableColumns));
        }
      },

      methods: {
        updateSuccess: function () {
          this.openDialog = false;
        }
      },

      components: {
        OrderConfig: PrintCommonOrderConfig
      },

      template: template
    };
  }();

  return {
    data: function () {
      return {
        loading: false,
        user: null,
        tableColumns: null,
        printOrders: [],
        sortFields: [],
        mode: 'edit',
        clauseContent: "",
        printOrderId: "",
        printOrderNo: "",
        pageConfig: {
          showTableHead: true
        }
      };
    },

    methods: {
      setTemplConfig: function () {
        var self = this;
        this.loading = true;
        var orderName = this.templateOrderName;
        return new Promise(function (resole, reject) {
          self.setUser().then(function () {
            CommonTemplateUtil.getTableTemplateConfig(orderName).then(function (config) {
              self.loading = false;

              var pageSize = config.size;
              pageSize = CommonTemplateUtil.getPageSize(pageSize);
              self.pageSize = {
                width: pageSize.width + 'px',
                minHeight: pageSize.height + 'px'
              };

              var textSize = config.textSize;
              for (const key in textSize) {
                var value = textSize[key];
                textSize[key] = {
                  fontSize: value + 'px'
                };
              }
              self.textSize = textSize;

              resole(config);
            }).catch(function (error) {
              self.loading = false;
              reject(error)
            });
          });
        });
      },

      setPrintId: function () {
        this.loading = true;
        var self = this;
        ajaxRequest('fileManager/getSerialNoForPrint').then(function (printOrderId) {
          self.printOrderId = printOrderId;
          self.printOrderNo = printOrderId;
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },

      setUser: function () {
        var self = this;
        return SysUtil.getUser().then(function (user) {
          self.user = user;
          return user;
        });
      },

      toPrintOrder: function (orderName) {
        this.mode = 'print';
        var self = this;
        this.getOrderImage(this.$refs['printArea'], orderName + '.png').then(function (imgUrl) {
          if (imgUrl === null) {
            self.toPrint();
            self.mode = 'edit';
            self.loading = false;
            self.setPrintId();
            return;
          }
          return self.saveOrderImage(imgUrl, orderName).then(function (msg) {
            self.toPrint();
            self.mode = 'edit';
            self.loading = false;
            self.setPrintId();
          });
        }).catch(function () {
          self.mode = 'edit';
          self.loading = false;
        });
      },

      toPrint: function () {
        var $print = $(this.$el).find('.print-area');
        $print = $print.clone();
        $print.css('display', 'none');
        $('#app').append($print);

        return new Promise(function (resole) {
          var $imgs = $print.find('img');
          var len = $imgs.length;
          if ($imgs.length > 0) {
            $imgs.on('load', function () {
              len--;
              if (len === 0) {
                window.print();
                $print.remove();
                resole(true);
              }
            });
            return;
          }
          window.print();
          $print.remove();
          resole(true);
        });
      },

      getOrderImage: function (el, name) {
        if (!domtoimage) {
          this.$alert('domtoimage文件加载失败', '信息');
          return Promise.resolve(null);
        }

        var self = this;
        return new Promise(function (resole) {
          self.$nextTick(function () {
            domtoimage.toBlob(el, {
              bgcolor: '#ffffff',
              quality: 1
            }).then(function (blob) {
              var file = {
                name: name,
                blob: blob
              };
              postImgsToQiniu('fileManager/getQiniuToken', file).then(function (imgUrl) {
                imgUrl = imgUrl[0];
                resole(imgUrl);
              });
            }).catch(function () {
              self.$alert('html转换为图片失败', '信息');
              resole(null);
            });
          });
        });
      },

      saveOrderImage: function (imgUrl, type) {
        var imgType;
        switch (type) {
          case 'purchaseOrder':
            imgType = 3;
            break;
          case 'prePurchaseOrder':
            imgType = 4;
            break;
          case 'outWarehouseOrder':
            imgType = 5;
            break;
          case 'outOrder':
            imgType = 6;
            break;
          case 'issueOrder':
            imgType = 7;
            break;
          case 'inWarehouseOrder':
            imgType = 9;
            break;
          case 'returnOrder':
            imgType = 10;
            break;
        }

        return ajaxRequest('fileManager/uploadFileForPrint', {
          order_no: this.printOrderId,
          type: imgType,
          file_name: this.printOrderNo,
          url: imgUrl
        }).then(function (msg) {
          return msg;
        });
      },

      getTableData: function (obj, column, index) {
        var config = column.config;
        if (config === undefined) {
          return '';
        }

        var type = config.type;
        if (type !== undefined) {
          if (type === 'lineNo') {
            return index + 1;
          }
        }

        var funName = config.funName;
        if (funName !== undefined) {
          return funName(obj);
        }

        var field = config.field;
        return obj[field];
      },

      toOrderData: function (tableColumn, type) {
        var sortType = tableColumn.sortType;
        var field = tableColumn.field
        if (sortType === type) {
          sortType = '';
        } else {
          sortType = type;
        }

        var sortFields = this.sortFields;
        sortFields = _.cloneDeep(sortFields);
        var index = sortFields.indexOf(field);
        if (index >= 0) {
          sortFields.splice(index, 1);
        }

        if (sortType !== '') {
          sortFields.unshift(field);
        }

        tableColumn.sortType = sortType;
        this.sortFields = sortFields;

        this.sortData();
        if (this.templateOrderName === 'purchaseOrder') {
          this.orderGroups = this.getOrderGroup();
        }
      },

      sortData: function () {
        var toSortData = this[sortDataField];
        if (SysUtil.isEmpty(toSortData)) {
          return;
        }

        var sortFields = this.sortFields;
        var printOrders = _.clone(toSortData);
        if (sortFields.length === 0) {
          this.printOrders = printOrders;
          return;
        }

        var tableColumns = this.config.tableColumns || this.tableColumns;
        var sortColumns = [];
        for (var i = 0; i < tableColumns.length; i++) {
          var tableColumn = tableColumns[i];
          var sortType = tableColumn.sortType;
          if (sortType === undefined || sortType === '') {
            continue;
          }

          var sortField = tableColumn.config.sortField;
          var field = tableColumn.field;
          if (sortField === undefined) {
            sortField = field;
          }
          sortType = sortType === 'ascending' ? 'asc' : 'desc';
          sortColumns.push({
            field: field,
            sortField: sortField,
            sortType: sortType
          });
        }
        sortColumns = _.sortBy(sortColumns, function (column) {
          return sortFields.indexOf(column.field);
        });

        printOrders = SysUtil.sortDataByColumns(printOrders, sortColumns);
        this.printOrders = printOrders;
      },

      getSortIndex: function (tableColumn) {
        var sortFields = this.sortFields;
        var field = tableColumn.field
        var index = sortFields.indexOf(field);
        if (index === -1) {
          return '';
        }
        return index + 1;
      },

      getAlignStyle: function (column) {
        var config = column.config;
        var styleFields = [{
          field: 'align',
          name: 'textAlign'
        }];
        var cellStyle = {};
        for (var i = 0; i < styleFields.length; i++) {
          var styleField = styleFields[i];
          var field = styleField.field;
          var value = config[field];
          if (value === undefined) {
            continue;
          }
          if (styleField.name !== undefined) {
            field = styleField.name;
          }
          cellStyle[field] = value;
        }

        return cellStyle;
      }
    },

    components: {
      ConfigButton: PrintCommonOrderConfigButton
    }
  };
};
